<!-- z-paging聊天输入框 -->

<template>
  <view class="chat-input-bar-container">
    <view class="chat-input-bar">
      <image @click="switchVoiceRecord" class="item-img" :src="images.voice"></image>
      <view class="chat-input-container">
        <!-- :adjust-position="false"必须设置，防止键盘弹窗自动上顶，交由z-paging内部处理 -->
        <view style="text-align: center;width: 100%" v-if="!showInput">按住说话</view>
        <input v-if="showInput"
               style="font-size: 32rpx"
               :confirm-hold="true"
               :always-embed="true"
               class="chat-input"
               v-model="msg"
               :adjust-position="false"
               confirm-type="send"
               type="text"
               @confirm="sendClick"/>
      </view>
      <!-- 表情图标（如果不需要切换表情面板则不用写） -->
      <view class="item-container">
        <image class="item-img" :src="images.emoji" @click="emojiChange"></image>
      </view>
      <view class="item-container">
        <image class="item-img" :src="images.more" @click="moreChange"></image>
      </view>
    </view>
    <!--  表情面板，这里使用height控制隐藏显示是为了有高度变化的动画效果（如果不需要切换表情面板则不用写） -->
    <view class="panel-container"
          :style="[{height: emojiShow ? '500rpx' : '0px'}]">
      <scroll-view scroll-y style="height: 100%;flex: 1;">
        <view class="emoji-panel">
          <text class="emoji-panel-text" v-for="(item, index) in emojisArr" :key="index" @click="emojiClick(item)">
            {{ item }}
          </text>
        </view>
      </scroll-view>
    </view>
    <view class="panel-container" :style="[{height: moreShow? '500rpx' : '0px'}]">
      <view class="tool-panel">
        <view>
          <view class="box" @tap="chooseImage">
            <image style="height: 60%;width: 60%" :src="images.photo"></image>
          </view>
          <text class="u-type-info">照片</text>
        </view>
        <view>
          <view class="box" @tap="chooseVideo">
            <image style="height: 60%;width: 60%" :src="images.camera"></image>
          </view>
          <text class="u-type-info">拍摄</text>
        </view>
        <view>
          <view class="box" @tap="chooseLocation">
            <image style="height: 60%;width: 60%" :src="images.location"></image>
          </view>
          <text class="u-type-info">位置</text>
        </view>
        <view>
          <view class="box" @tap="chooseFile">
            <image style="height: 60%;width: 60%" :src="images.file"></image>
          </view>
          <text class="u-type-info">文件</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/config'
import images from '@/utils/images'

export default {
  name: "chat-input-bar",
  data() {
    return {
      showInput: true,
      mapFlag: false,
      images,
      msg: '',
      config,
      // 表情数组（如果不需要切换表情面板则不用写）
      emojisArr: ['😊', '😁', '😀', '😃', '😣', '😞', '😩', '😫', '😲', '😟', '😦', '😜', '😳', '😋', '😥', '😰', '🤠', '😎', '😇', '😉', '😭', '😈', '😕', '😏', '😘', '😤', '😡', '😅', '😬', '😺', '😻', '😽', '😼', '🙈', '🙉', '🙊', '🔥', '👍', '👎', '👌', '✌️', '🙏', '💪', '👻'],
      // 当前input focus（如果不需要切换表情面板则不用写）
      focus: false,
      moreShow: false,
      emojiShow: false,
    };
  },
  methods: {
    switchVoiceRecord() {
      this.moreShow = false
      this.emojiShow = false
      this.showInput = !this.showInput

    },
    chooseFile() {
      uni.chooseMessageFile({
        count: 1, // 文件总数
        type: 'file', // 文件类型
        success: (re) => {
          uni.showLoading({
            title: '发送中...'
          });
          for (let file of re.tempFiles) {
            uni.uploadFile({
              name: "file",
              url: config.baseUrl + '/common/upload',
              filePath: file.path,
              success: (re) => {
                let res = JSON.parse(re.data)
                let msg = {type: "file", url: res.url, fileName: file.name, size: file.size}
                this.$emit('send', msg);
              },
              fail: (re) => {
                console.log(re)
              },
              complete: function () {
                uni.hideLoading();
              }
            });
          }
        },
        fail: (err) => {
          // 取消上传
          //console.log(err);
        }
      });
    },
    chooseLocation() {
      uni.chooseLocation({
        success: e => {
          if (e.name) {
            let msg = {type: "location", msg: e.name, lng: e.longitude, lat: e.latitude, address: e.address}
            this.$emit('send', msg);
          }
        }
      })
    },
    // 更新了键盘高度（如果不需要切换表情面板则不用写）
    updateKeyboardHeightChange(res) {
      if (res.height > 0) {
        //重置状态
        this.emojiShow = false;
        this.moreShow = false;
      }
    },
    // 用户尝试隐藏键盘，此时如果表情面板在展示中，应当隐藏表情面板，如果是键盘在展示中不用处理，z-paging内部已经处理（如果不需要切换表情面板则不用写）
    hidedKeyboard() {
      //重置状态
      this.emojiShow = false;
      this.moreShow = false;
    },
    chooseVideo() {
      uni.chooseVideo({
        count: 1,
        sourceType: ['camera', 'album'],
        success: res => {
          uni.showLoading({
            title: '发送中...'
          });
          let path = res.tempFilePath;
          uni.uploadFile({
            name: "file",
            url: config.baseUrl + '/common/upload',
            filePath: path,
            success: (re) => {
              let rsp = JSON.parse(re.data)
              let msg = {type: "video", url: rsp.url, width: res.width, height: res.height, cover: rsp.cover}
              this.setVideoSize(msg)
              this.$emit('send', msg);
            },
            fail: (re) => {
              console.log(re)
            },
            complete: function () {
              uni.hideLoading();
            }
          });
        }
      });
    },
    chooseImage() {
      uni.chooseImage({
        sourceType: ['album', 'camera'],
        sizeType: ['compressed'],
        success: chooseImages => {
          uni.showLoading({
            title: '发送中...'
          });
          for (let image of chooseImages.tempFilePaths) {
            uni.getImageInfo({
              src: image,
              success: (info) => {
                uni.uploadFile({
                  name: "file",
                  url: config.baseUrl + '/common/upload',
                  filePath: image,
                  success: (re) => {
                    let res = JSON.parse(re.data)
                    let msg = {type: "image", url: res.url, width: info.width, height: info.height}
                    this.setImageSize(msg)
                    this.$emit('send', msg);
                  },
                  fail: (re) => {
                    console.log(re)
                  },
                  complete: function () {
                    uni.hideLoading();
                  }
                });
              }
            });
          }
        }
      })
    },
    setImageSize(msg) {
      let maxW = uni.upx2px(350); //350是定义消息图片最大宽度
      let maxH = uni.upx2px(350); //350是定义消息图片最大高度
      if (msg.width > maxW || msg.height > maxH) {
        let scale = msg.width / msg.height;
        msg.width = scale > 1 ? maxW : maxH * scale;
        msg.height = scale > 1 ? maxW / scale : maxH;
      }
      return msg;
    },
    setVideoSize(msg) {
      let maxW = uni.upx2px(400); //350是定义消息图片最大宽度
      let maxH = uni.upx2px(400); //350是定义消息图片最大高度
      if (msg.width > maxW || msg.height > maxH) {
        let scale = msg.width / msg.height;
        msg.width = scale > 1 ? maxW : maxH * scale;
        msg.height = scale > 1 ? maxW / scale : maxH;
      }
      return msg;
    },
    moreChange() {
      this.emojiShow = false
      this.moreShow = !this.moreShow
    },
    // 点击了切换表情面板/键盘（如果不需要切换表情面板则不用写）
    emojiChange() {
      this.moreShow = false
      this.emojiShow = !this.emojiShow
    },
    // 点击了某个表情，将其插入输入内容中（如果不需要切换表情面板则不用写）
    emojiClick(text) {
      this.msg += text;
    },

    // 点击了发送按钮
    sendClick() {
      if (!this.msg.length) return;
      this.$emit('send', {type: "text", msg: this.msg});
      this.msg = '';
    }
  }
}
</script>

<style lang="scss" scoped>


.chat-input-bar {
  display: flex;
  flex-direction: row;
  align-items: center;
  border-top: solid 1px #f5f5f5;
  background-color: #f8f8f8;

  padding: 10rpx 20rpx;
}

.chat-input-container {
  flex: 1;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  padding: 15rpx;
  background-color: white;
  border-radius: 10rpx;
}

.chat-input {
  flex: 1;
  font-size: 28rpx;
}

.item-container {
  width: 54rpx;
  height: 54rpx;
  margin: 10rpx 0rpx 10rpx 20rpx;
}

.item-img {
  width: 60rpx;
  height: 60rpx;
}

.panel-container {
  background-color: #f8f8f8;
  overflow: hidden;
  transition-property: height;
  transition-duration: 0.28s;
  /* #ifndef APP-NVUE */
  will-change: height;
  /* #endif */
}

.emoji-panel {
  font-size: 30rpx;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  flex-wrap: wrap;
  padding-right: 10rpx;
  padding-left: 15rpx;
  padding-bottom: 10rpx;
}

.tool-panel {
  margin-top: 5%;
  text-align: center;
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .box {
    box-shadow: 0 0 8px rgba(114, 118, 206, 0.2700);
    width: 18vw;
    height: 18vw;
    border-radius: 30upx;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 3vw 2vw 3vw;
  }
}

.emoji-panel-text {
  font-size: 50rpx;
  margin-left: 15rpx;
  margin-top: 20rpx;
}
</style>